package current.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo3 {
    private static ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // 一个SimpleDateFormat对象(该对象为内存拷贝)对应一个线程，既节约内存又保证线程安全
    public static ThreadLocal<SimpleDateFormat> formatThreadLocal = new ThreadLocal<>(){
        @Override
        protected SimpleDateFormat initialValue() {
            // 只会在第一次初始化时创建对象，以后的调用都直接返回相同初始化时的值
            return new SimpleDateFormat("yyyy-MM-dd");
        }

        @Override
        public SimpleDateFormat get() {
            // 每个线程将会获得它自身的拷贝对象
            return super.get();
        }
    };

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            int id = i;
            pool.submit(() -> {
                String birthDate = new ThreadLocalDemo3().birthDate(id);
                System.out.println(birthDate);
            });
        }

        TimeUnit.SECONDS.sleep(1);

        // 为防止因线程池导致内存泄露，手动清空
        formatThreadLocal.remove();
    }

    public String birthDate(int userId) {
        Date birthDate = birthDateFromDB(userId);
        final SimpleDateFormat sdf = ThreadLocalDemo3.formatThreadLocal.get();
        return sdf.format(birthDate);
    }

    public static Date birthDateFromDB(int userId) {
        return new Date();
    }
}
